package com.yager.controller;

import com.github.pagehelper.PageInfo;
import com.yager.model.Comment;
import com.yager.model.House;
import com.yager.model.Page;
import com.yager.model.User;
import com.yager.service.CommentService;
import com.yager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;

    @RequestMapping("/addNewComment")
    public String addNewComment(HttpServletRequest req, HttpSession session, String houseComment, String houseid){

        User user=(User) session.getAttribute("user");

        commentService.addNewComment(user.getUserid(),houseid,houseComment);

        return "comment/houseComment";
    }

    @RequestMapping("/getHouseComments")
    public String getHouseComment(HttpServletRequest req,HttpSession session,@RequestParam(defaultValue = "1") Integer pageNo){
        House house=(House) session.getAttribute("Onehouse");

/*        if(!commentService.isHouseHasComment(house.getHouseid()));*/

        PageInfo<Comment> commentPageInfo=commentService.getAllCommentByHouseId(house.getHouseid(),pageNo);
        List<Comment> commentList=commentPageInfo.getList();
        List<User> userList=new ArrayList<>();
        User u=null;

        for(Comment c : commentList){
            u=userService.getUserById(c.getUserid());
            userList.add(u);
        }
        PageInfo<User> userPageInfo = new PageInfo<>(userList);
        session.setAttribute("houseCommentUsers",userPageInfo);
        session.setAttribute("houseCommentPage",commentPageInfo);
        return "comment/houseComment";
    }

    @RequestMapping("/getOrderComments")
    public String getOrderComment(HttpServletRequest req,HttpSession session,@RequestParam(defaultValue = "1") Integer pageNo){
        String orderid=null;

        if(!commentService.isOrderHasComment(orderid)) return null;

        PageInfo<Comment> commentPageInfo=commentService.getAllCommentByOrderId(orderid,pageNo);
        List<Comment> commentList=commentPageInfo.getList();
        List<User> userList=new ArrayList<>();
        User u=null;

        for(Comment c : commentList){
            u=userService.getUserById(c.getUserid());
            userList.add(u);
        }

        session.setAttribute("orderCommentUsers",userList);
        session.setAttribute("orderCommentPage",commentPageInfo);
        return null;
    }





}
